<?php
namespace app\interfaces\controller;

use think\Db;
use think\Cache;
use think\Request;
use think\Exception;
use think\Controller;
use app\interfaces\model\Shop as ShopModel;
use app\interfaces\model\Limited as LimitedModel;
use app\interfaces\model\QuotHour as QuotHourModel;
use app\interfaces\model\RushHour as RushHourModel;
use app\interfaces\model\ShopGoods as ShopGoodsModel;
use app\interfaces\model\LimitedType as LimitedTypeModel;
use app\interfaces\model\ShopSpecAttr as ShopSpecAttrModel;
use app\interfaces\model\MemberBrowse as MemberBrowseModel;
use app\interfaces\model\MemberCollect as MemberCollectModel;
use app\interfaces\model\ShopGoodsCombo as ShopGoodsComboModel;
use app\interfaces\model\ShopGoodsEvaluate as ShopGoodsEvaluateModel;
use app\interfaces\model\ShopGoodsComboSelected as ShopGoodsComboSelectedModel;

class ShopGoods extends Controller
{

    protected $beforeActionList = [
        'show_record' => ['only' => 'view_ss'],
    ];


    public function collect(){
        $member_id = Request::instance()->param('member_id');
        $goods_id = Request::instance()->param('collect_id');
        $find = Db::name('member_collect')->where(['member_id' => $member_id,'collect_id' => $goods_id])->find();

        if($find){
            $r = Db::name('member_collect')->where(['member_id' => $member_id,'collect_id' => $goods_id])->delete();
            if($r){
                return ['code' => 200,'message' => '收藏取消成功','collect' => 1];
            }
        }
        $ret = Db::name('member_collect')->insert(['member_id' => $member_id,'collect_id' => $goods_id,'create_time' => date('Y-m-d H:i:s',time())]);
        if($ret){
            return ['code' => 200,'message' => '收藏成功','collect' => 2];
        }
    }

    public function cancel_collect(){
        $member_id = Request::instance()->param('member_id');
        $goods_id = Request::instance()->param('collect_id');
        $ret = Db::name('member_collect')->where(['member_id' => $member_id,'collect_id' => $goods_id])->delete();
        if($ret){
            return ['code' => 200,'message' => '取消收藏成功'];
        }
        return ['code' => 0,'message' => 'fail'];
    }

    public function my_collect(){
        $member_id = Request::instance()->param('member_id');
        $select = Db::name('member_collect')
            ->alias('member_collect')
            ->where(['member_collect.member_id' => $member_id])
            ->join('shop_goods','member_collect.collect_id = shop_goods.id')
            ->field('shop_goods.id,shop_goods.picUrl,shop_goods.title,shop_goods.price,member_collect.create_time')
            ->paginate(6);
        return ['code' => 200,'message' => '我的收藏列表','data' => $select];
    }
    /*
     * 用户端 - 商品列表
     */
    public function goods_list()
    {

        // 获取参数
        $inquire = Request::instance()->param();

        // 搜索条件
        $condition['state'] = ['eq', 1];

        // 是否开启审核

        // 条件
        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];
        if (!empty($inquire['goods_id'])) $condition['goods_id'] = ['eq', $inquire['goods_id']];
        if (!empty($inquire['class_id'])) $condition['goods_str'] = ['like', '%,' . $inquire['class_id'] . ',%'];
        if (!empty($inquire['brand_id'])) $condition['brand_id'] = ['eq', $inquire['brand_id']];
        if (!empty($inquire['freight_type'])) $condition['freight_type'] = ['eq', '2'];
        if (!empty($inquire['low_price'])) $condition['price'] = ['egt', $inquire['low_price']];
        if (!empty($inquire['high_price'])) $condition['price'] = ['elt', $inquire['high_price']];
        if (!empty($inquire['low_price']) && $inquire['high_price']) $condition['price'] = [['egt', $inquire['low_price']], ['elt', $inquire['high_price']]];

        // 排序
        $sort = ['sale_number' => 'desc'];

        // 排序传参
        if (!empty($inquire['order']) && $inquire['order'] == 'sale_number' ){$sort = ['sale_number' => 'desc'];}
        if (!empty($inquire['order']) && $inquire['order'] == 'high_price' ){$sort = ['price' => 'desc'];}
        if (!empty($inquire['order']) && $inquire['order'] == 'lower_price' ){$sort = ['price' => 'asc'];}
        if (!empty($inquire['order']) && $inquire['order'] == 'evaluate_number' ){$sort = ['evaluate_number' => 'desc'];}


        $result = ShopGoodsModel::where($condition)->field('id,title,price,thumb_img,sale_number,rebate_percentage,goods_attr')
            ->order($sort)->paginate(10, false, ['query' => $inquire]);
        //echo Db::getlastSql();


        return ['code' => 200, 'message' => '成功', 'data' => $result];


    }

    /*
     * 用户端 - 商品详情
     * @param  string $id 唯一标示
     */
    public function view()
    {
        // 获取参数

        $id = Request::instance()->param('id');
        $user_id = Request::instance()->param('user_id');
        $city = Request::instance()->param('city', '哈尔滨市');
        $hour = (int)date('H');
        $ini['end_time'] = ['gt', $hour];
        $quot_id = (new QuotHourModel)->where($ini)->field('id,name,start_time,end_time')->find();
        if (empty($id)) throw new Exception('not Empty');
        // 详细信息
        $info = ShopGoodsModel::where(['s.id' => $id])->alias('s')->field('s.id,s.member_id,s.title,s.sale_number,s.state,s.status,s.picUrl,s.goods_attr,s.goods_id,s.rebate_percentage,s.picArr,s.content,s.charges,s.goods_attr,s.create_time as collection_status,s.price,s.market_price,s.rebate_percentage,s.freight_type,s.freight,s.sale_number')
            ->join('shop_spec_attr ssa', 's.id = ssa.goods_id')->field('max(ssa.price) as big_price, min(ssa.price) as small_price,max(ssa.market_price) as big_marketPrice,min(ssa.market_price) as small_marketPrice')->find();
        $info['price_status'] = 1;
        $info['special'] = 0;
        // 限时抢购特价判断
        $son['goods_id'] = $id;
        $son['rush_id'] = $quot_id['id'];
        $limit_goods = (new RushHourModel())->where($son)->find();
        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        if ($limit_goods) {
            // 限时抢购价格
            $info['special'] = $limit_goods['price'];
            $info['robbed'] = $limit_goods['purchase_number'];
            // 限时抢购结束时间
            $info['limited_time'] = $beginToday + ($quot_id['end_time'] * 3600);
            $info['now_time'] = time();
            $info['price_status'] = 2;
        }
        // 天天特价判断
        $special_goods = (new GroupGoodsModel())->where('goods_id', $id)->find();
        if ($special_goods) {
            $info['special'] = $special_goods['price'];
            $info['price_status'] = 3;
        }
        $info['picArr'] = (array)unserialize($info['picArr']);
        // 评论
        $info['evaluate'] = (new ShopGoodsEvaluateModel())->where(['goods_id' => $id])->count();
        $info['evaluate_info'] = Db::view('shop_goods_evaluate', 'member_id,content,grade,attr,status,create_time')
            ->view('member', 'id,nickname,avatar', 'member.id = shop_goods_evaluate.member_id')
            ->where(['goods_id' => $id])->order(['create_time' => 'desc'])->find();
        if (!$info['evaluate_info']){
            $info['evaluate_info'] = '';
        }
        // 店铺
        $info['shop'] = ShopModel::where(['member_id' => $info['member_id']])->field('logo,title,description,phone,type')->find();
        // 优惠套餐
        $info['combo_id'] = (int)ShopGoodsComboSelectedModel::where(['goods_id' => $id])->value('combo_id');
        // 降价通知判断
        $info['reduction'] = (new PriceReduction())->where(['goods_id'=>$id,'member_id'=>$user_id])->value('id')?1:2;
        // 不存在
        if (empty($info['combo_id'])) $info['combo'] = [];
        // 存在
        $info['combo_ids'] = ShopGoodsComboSelectedModel::where(['combo_id' => $info['combo_id']])->field('goods_id')->select();
        $info['combo'] = "";
        $ss= [];
        foreach ($info['combo_ids'] as &$value) {
            $ss[]= ShopGoodsModel::where(['id' => $value['goods_id']])->field('id,title,thumb_img,price')->find();
        }
        $info['combo'] = $ss;
        // 店铺推荐
        $shop_goods = ShopGoodsModel::where(['member_id' => $info['member_id'], 'recommend' => '1', 'status' => 1, 'state' => 1])->field('id,title,picUrl,sale_number,price')->order(['sort' => 'desc', 'create_time' => 'desc'])->paginate(6);
        // 地址运费
        $freight = [];
        $address = [];
        if ($user_id) {
            $find = Db::name('member_address')->where(['member_id' => $user_id, 'status' => 1])->field('id,name,phone,area_info,template_id,address')->find();
            $address = Db::name('member_address')->where(['member_id' => $user_id])->field('id,name,phone,area_info,template_id,address')->select();
            if ($find) {
                $con['area_id'] = ['like', '%,' . $find['template_id'] . ',%'];
                $con['member_id'] = $info['member_id'];
                $freight['price'] = Db::name('freight_template')->where($con)->value('price');
                if (empty($freight['price'])) {
                    $freight['price'] = 0;
                }
                $freight['address'] = $find['area_info'] . $find['address'];
                $freight['ios_address'] = $find;
                $freight['address_id'] = $find['id'];
            } else {
                $find = Db::name('member_address')->where(['member_id' => $user_id])->field('id,name,phone,area_info,template_id,address')->find();
                if ($find) {
                    $con['area_id'] = ['like', '%,' . $find['template_id'] . ',%'];
                    $con['member_id'] = $info['member_id'];
                    $freight['price'] = Db::name('freight_template')->where($con)->value('price');
                    $freight['address'] = $find['area_info'] . $find['address'];
                    $freight['ios_address'] = $find;
                    $freight['address_id'] = $find['id'];
                    if (empty($freight['price'])) {
                        $freight['price'] = 0;
                    }
                } else {
                    $freight['price'] = 0;
                    $freight['ios_address'] = "";
                    $freight['address_id'] = "";
                    $freight['address'] = "";
                }
            }
        } else {
            $con['member_id'] = $info['member_id'];
            $area = Db::name('area')->where('area_name', $city)->find();
            $con['area_id'] = ['like', '%,' . $area['area_id'] . ',%'];
            $con['member_id'] = $info['member_id'];
            $freight['price'] = Db::name('freight_template')->where($con)->value('price');
            $freight['address_id'] = 0;
            if (empty($freight['price'])) {
                $freight['price'] = 0;
                $freight['address'] = "";
                $freight['ios_address'] = ['id' => '', 'name' => '', 'phone' => '', 'area_info' => '', 'template_id' => '', 'address' => ''];
            }
        }
        return ['code' => 200, 'message' => '成功', 'data' => $info, 'goods_list' => $shop_goods, 'freight' => $freight, 'address' => $address];
    }


    // 测试商品详情
    public function view_ss()
    {
        // 获取参数

        $id = Request::instance()->param('id');
        $user_id = Request::instance()->param('user_id');
        if (empty($id)) throw new Exception('not Empty');

        // 详细信息
        $info = \app\common\model\ShopGoods::where(['id' => $id])->field('id,label,member_id,title,price,sale_number,picArr,goods_attr,freight')->find();



        halt($info->toArray());
        $info['picArr'] = (array)unserialize($info['picArr']);
        // $info['goods_attr'] = arrayChange(unserialize($info['goods_attr']), 'title', 'list');

        // 评论
        $info['evaluate'] = (new ShopGoodsEvaluateModel())->where(['goods_id' => $id])->count();
//        $info['evaluate_info'] = Db::view('shop_goods_evaluate', 'member_id,content,grade,attr,status,create_time,picArr')
//            ->view('member', 'id,nickname,avatar', 'member.id = shop_goods_evaluate.member_id')
//            ->where(['goods_id' => $id])
//            ->order(['create_time' => 'desc'])
//            ->paginate(6)->each(function($item,$key){
//                $item['picArr'] = 3123;
//                return $item;
//            });
        $info['evaluate_info'] = (new ShopGoodsEvaluateModel())
            ->alias('a')
            ->where(['goods_id' => $id])
            ->where('a.status',1)
            ->order('a.create_time','desc')
            ->join('member','a.member_id = member.id')
            ->field('a.id,a.title,a.content,a.picArr,a.create_time,member.avatar,member.nickname')
            ->paginate(6)->each(function($item,$key){
                $item['picArr'] = (unserialize($item['picArr']) == false) ? [] : unserialize($item['picArr']);
                $item['create_time'] = date('Y-m-d H:i:s',$item['create_time']);
            });
        $collect = 1;
        $c = Db::name('member_collect')->where(['member_id' =>$user_id,'collect_id' => $id])->find();
        if($c) $collect = 2;
        // 店铺
        //$info['shop'] = ShopModel::where(['member_id' => $info['member_id']])->field('logo,title,description,phone,type,url qq')->find();



        // 店铺推荐


        return ['code' => 200, 'message' => '成功','collect' => $collect ,'data' => $info];
    }

    // public function recommend()
    // {
    //     // 获取参数
    //     $id = Request::instance()->param('id');
    //
    //     $info_id = ShopGoodsModel::where(['id' => $id])->value('member_id');
    //
    //     // 店铺推荐
    //     $shop_goods = ShopGoodsModel::where(['member_id' => $info_id, 'recommend' => '1'])->field('id,title,picUrl,sale_number,price')->limit(4)->select();
    //
    //     return ['code' => 200, 'message' => '成功', 'goods_list' => $shop_goods];
    //
    // }

    /*
     * 用户端 - 改变地址改变运费
     * @param  string $attr 属性
     * @param  string $goods_id 商品ID
     */
    public function charge_freight()
    {
        // 获取数据
        $id = Request::instance()->param('freight_id');
        $shop_id = Request::instance()->param('shop_id');

        $find = Db::name('member_address')->where('id', $id)->field('id,name,phone,area_info,template_id,address')->find();

        $con['area_id'] = ['like', '%,' . $find['template_id'] . ',%'];
        $con['member_id'] = $shop_id;
        $freight['price'] = Db::name('freight_template')->where($con)->value('price');
        $freight['address'] = $find['area_info'].$find['address'];
        $freight['ios_address'] = $find;
        if (empty($freight['price'])){
            $freight['price'] = 0;
        }

        return ['code' => 200, 'message' => '成功', 'freight' => $freight];

    }


    /*
     * 用户端 - 属性获取金钱和数量
     * @param  string $attr 属性
     * @param  string $goods_id 商品ID
     */
    public function attr_gain()
    {
        // 获取参数
        $attr = Request::instance()->param('attr');
        $goods_id = Request::instance()->param('goods_id');

        if (empty($attr) || empty($goods_id)) throw new Exception('not Empty');

        // 读取参数
        $result = ShopSpecAttrModel::where(['attribute' => $attr, 'goods_id' => $goods_id])->field('price,inventory')->find();

        return ['code' => 200, 'message' => '成功', 'data' => $result];
    }

    /*
     * 用户端 - 套餐列表
     * @param  string $combo_id 套餐ID
     */
    public function combo_list()
    {
        // 获取参数
        $combo_id = Request::instance()->param('combo_id');
        $shop['shop_id'] = Request::instance()->param('shop_id');
        $shop['shop_title'] = Request::instance()->param('shop_title');

        if (empty($combo_id) || empty($shop['shop_id']) || empty($shop['shop_title'])) throw new Exception('not Empty');

        // 读取参数
        $result = ShopGoodsComboSelectedModel::where('combo_id',$combo_id)->field('goods_id,goods_attr_id')->select();

        $data = [];
        foreach ($result as $key => &$value) {
            $attr = ShopSpecAttrModel::where(['id' => $value['goods_attr_id']])->value('attribute');
            $data[$key] = ShopGoodsModel::where(['id' => $value['goods_id']])->field('id,title,price,thumb_img,rebate_percentage,goods_attr')->find();
            $data[$key]['attr'] = $attr;

        }

        // 套餐价格
        $combo = ShopGoodsComboModel::where(['id' => $combo_id])->field('combo_price,total')->find();

        return ['code' => 200, 'message' => '成功', 'data' => $data, 'combo' => $combo, 'shop' => $shop];
    }

    /*
     * 用户端 - 取消收藏商品
     * @param  string $id       商品ID
     * @param  string $user_id  会员ID
     */
    public function collect_del()
    {

        $id = Request::instance()->param('id');
        $user_id = Request::instance()->param('user_id');

        if (empty($id) || empty($user_id)) throw new Exception('not Empty');


        // 取消收藏
        $result = MemberCollectModel::where(['collect_id' => $id, 'member_id' => $user_id])->delete();

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '网络繁忙'];

    }

    /*
     * 用户端 - 获取库存
     * @param  string $id       商品ID
     * @param  string $attr     属性
     */
    public function gain_inventory()
    {

        $id = Request::instance()->param('id');
        $attr = Request::instance()->param('attr', '');

        if (empty($id)) throw new Exception('not Empty');

        if (empty($attr)) {
            $inventory = ShopGoodsModel::where(['id' => $id])->value('inventory');
        } else {
            $inventory = ShopSpecAttrModel::where(['goods_id' => $id, 'attribute' => $attr])->value('inventory');
        }

        return ['code' => 200, 'message' => '成功', 'inventory' => $inventory];

    }


    public function flash_sale()
    {
        $goods_id = Request::instance()->param('goods_id');

        if (empty($goods_id)) throw new Exception('not Empty');
        $hour = (int)date('H');
        $ini['end_time'] = ['gt', $hour];
        $quot_id = (new QuotHourModel)->where($ini)->field('id,name,start_time,end_time')->find();
        $son['goods_id'] = $goods_id;
        $son['rush_id'] = $quot_id['id'];
        $limit_goods = (new RushHourModel())->where($son)->find();

        if ($limit_goods) {
            if ($limit_goods['number'] > 0) {
                return ['code' => 200, 'message' => 'Ok'];
            } else {
                return ['code' => 401, 'message' => '抢购数量不足'];
            }

        } else {
            return ['code' => 401, 'message' => '已过抢购时间'];
        }

    }


    /*
     * 用户端 - 浏览记录 and 增加点击量
     * @param  string $user_id  会员ID
     * @param  string $id       商品ID
     */
    protected function show_record()
    {
        $user_id = Request::instance()->param('user_id');
        $id = Request::instance()->param('id');

        if (!empty($user_id) && !empty($id)) {

            $model = new MemberBrowseModel();

            $find = $model->where(['goods_id' => $id, 'create_time' => date('Y-m-d', time())])->value('id');

            if (empty($find)) {

                $model->save(['member_id' => $user_id, 'goods_id' => $id, 'create_time' => date('Y-m-d', time())]);

            }

        }

        $goods_model = new ShopGoodsModel();
        // 增加点击量
        $goods_model->where(['id' => $id])->setInc('hits', 1, 5);
        // 增加今日访问量
        $goods_model->where(['id' => $id])->setInc('pv', 1, 5);
    }

}
